package com.frxuexi.sign.view

import android.annotation.SuppressLint
import android.text.TextUtils
import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.blankj.utilcode.util.TimeUtils
import com.frxuexi.lib_base.MyTitleBar
import com.frxuexi.lib_base.RouterPath
import com.frxuexi.lib_base.UiState
import com.frxuexi.sign.R
import com.frxuexi.sign.SignEntity
import com.frxuexi.sign.SignIntent
import com.frxuexi.sign.SignViewModel
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat

@SuppressLint("SimpleDateFormat")
@Composable
fun SignPage(navHostController: NavHostController, vm: SignViewModel = hiltViewModel()) {
    var list = remember {
        SnapshotStateList<SignEntity>()
    }

    LaunchedEffect(key1 = "", block = {
        launch {
            vm.uiState.collect {
                when (it) {
                    is UiState.onSuccess<*> -> {
                        list.addAll(it.data as Collection<SignEntity>)

                    }

                    is UiState.onError -> {
                        Log.i("===", it.msg)
                    }

                    else -> {}
                }
            }
        }

        vm.sendIntent(SignIntent.getSigns(mapOf("userId" to 1, "page" to 1)))
    })

    Scaffold(bottomBar = {
        var signState by remember {
            mutableStateOf("签到")
        }
        var isEnable by remember {
            mutableStateOf(true)
        }

        val kv = MMKV.defaultMMKV()
        Button(
            onClick = {
               val time =SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis())
                if (signState == "签到") {
                    signState = "签退"
                    kv.encode("sign", "sign,$time")
                } else {//签退事件
                    isEnable = false
                    kv.encode("sign", "sout,$time")
                }
                navHostController.navigate(RouterPath.SIGN_COMMIT_PAGE)
            },
            enabled = isEnable,
//            colors = ButtonDefaults.buttonColors(containerColor = Color.Blue),
            modifier = Modifier
                .fillMaxWidth()
                .padding(10.dp, 5.dp)
        ) {

            LaunchedEffect(key1 = "", block = {
                //sign/sout,2024-08-27 14:15:30
                //页面进来先获取之前打卡的状态和时间
                val sign = kv.decodeString("sign", "").toString()
                if (TextUtils.isEmpty(sign)) {//如果为空，说明是第一次进来签到，显示签到字样
                    signState = "签到"
                } else {
                    val split = sign.split(",")
                    val s = split[0]//之前打卡的状态
                    val time = split[1].substring(0,10)//之前打卡的时间
                    val currentTime =
                        SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis())//获取当前年月日

                    if (time == currentTime) {//是今天打过卡
                        if (s == "sign") {//说明已经打过签到卡
                            signState = "签退"
                        } else {//说明已经打过签退卡，按钮不可用
                            isEnable = false
                        }
                    } else {
                        signState = "签到"
                    }
                }
            })


            Text(text = signState)
        }
    }) {
        Column(Modifier.padding(it)) {
            MyTitleBar(title = "考勤", navHostController = navHostController)
            Row(
                Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 20.dp, 10.dp),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                val week = TimeUtils.getChineseWeek(System.currentTimeMillis())
                Text(text = "时间$week")
                Text(text = "考勤规则")
            }

            LazyColumn(verticalArrangement = Arrangement.spacedBy(10.dp), content = {
                items(list) {
                    SignItem(entity = it)
                }
            })
        }
    }

}

@Composable
fun SignItem(entity: SignEntity) {
    val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(entity.signTime)
    Text(
        text = time, modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 10.dp)
            .background(colorResource(id = R.color.lightblue))
            .padding(15.dp)
    )
}